package fr.utbm.to52.android_bibtex.controller;

import java.io.File;
import java.io.IOException;

import android.app.ProgressDialog;
import android.content.Intent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import fr.utbm.to52.android_bibtex.R;
import fr.utbm.to52.android_bibtex.main.AddEntryActivity;
import fr.utbm.to52.android_bibtex.main.FieldActivity;
import fr.utbm.to52.android_bibtex.main.MainActivity;
import fr.utbm.to52.android_bibtex.model.entry.EntryList;

public class MainController implements OnItemClickListener {

	private final MainActivity activity;
	private ProgressDialog saveProgressDialog;

	public MainController(MainActivity activity) {
		this.activity = activity;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		//		FieldActivity.entry = EntryList.getInstance().getEntry(((TwoLineListItem) view).getText1().getText().toString());
		//		Intent new_intent = new Intent(this.activity, FieldActivity.class);
		//		new_intent.putExtra("createMode", false);
		//		this.activity.startActivity(new_intent);
		final ListView lv = (ListView) this.activity.findViewById(R.id.listViewEntries);
		Object o = lv.getItemAtPosition(position);
		ListViewItem lvi = (ListViewItem) o;
		FieldActivity.entry = EntryList.getInstance().getEntry(lvi.getKey());
		Intent new_intent = new Intent(this.activity, FieldActivity.class);
		new_intent.putExtra("createMode", false);
		this.activity.startActivity(new_intent);
	}

	public boolean itemSelectedAction(MenuItem item, final File outfile) {
		switch (item.getItemId()) {
		case R.id.menu_addEntry:
			this.activity.startActivity(new Intent(this.activity, AddEntryActivity.class));
			return true;
		case R.id.menu_saveEntryList:
			MainActivity.entryListChanged = false;
			final BibtexWriter bw = new BibtexWriter();
			this.saveProgressDialog = ProgressDialog.show(this.activity, "Saving...", "Please wait.");
			new Thread() {
				@Override
				public void run() {
					try {
						bw.write(outfile);
					} catch (IOException e) {
						e.printStackTrace();
					}
					MainController.this.saveProgressDialog.dismiss();
				}
			}.start();
			this.activity.invalidateOptionsMenu();
			return true;
		default:
			return false;
		}
	}

}
